Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
The getopts npm package is a lightweight and fast option parser for Node.js. It is used to parse command-line options and arguments in a simple and efficient manner.
Basic Option Parsing
This feature allows you to parse command-line options and arguments. The code sample demonstrates how to use getopts to parse the command-line arguments passed to a Node.js script.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2));
console.log(options);
Default Values
This feature allows you to set default values for options. The code sample shows how to provide default values for the 'name' and 'age' options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
default: {
name: 'defaultName',
age: 25
}
});
console.log(options);
Aliases
This feature allows you to define aliases for options. The code sample demonstrates how to set up aliases for the 'name' and 'age' options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
alias: {
n: 'name',
a: 'age'
}
});
console.log(options);
Boolean Options
This feature allows you to specify which options should be treated as boolean. The code sample shows how to define 'verbose' and 'debug' as boolean options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
boolean: ['verbose', 'debug']
});
console.log(options);
Unknown Option Handling
This feature allows you to handle unknown options. The code sample demonstrates how to log an error message for unknown options and prevent them from being included in the parsed options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
unknown: (option) => {
console.error(`Unknown option: ${option}`);
return false;
}
});
console.log(options);
Minimist is a popular option parser for Node.js that is similar to getopts. It provides a simple way to parse command-line arguments and supports features like default values, aliases, and boolean options. Compared to getopts, minimist is more widely used and has a larger community.
Yargs is a powerful option parser for Node.js that offers a rich set of features for building command-line tools. It supports advanced features like command handling, middleware, and interactive prompts. Yargs is more feature-rich compared to getopts, making it suitable for more complex CLI applications.
Commander is a comprehensive option parser and command-line interface (CLI) framework for Node.js. It provides a robust set of features for defining commands, options, and arguments. Commander is more feature-complete compared to getopts and is ideal for building complex CLI applications with multiple commands.
Parse CLI arguments.
minimist
and clones.Break up command-line arguments into key-value pairs for easy look-up and retrieval. Built upon utility conventions that have been used for decades, Getopts sane defaults help you write CLI tools that look and feel like the real deal.
$ example --type=module -o main.js *.{js,json}
import getopts from "getopts"
const options = getopts(process.argv.slice(2), {
alias: {
output: ["o", "f"],
type: "t",
},
})
The result is an object populated with all the parsed arguments.
{
_: ["index.js", "package.json"],
output: "main.js",
type: "module",
o: "main.js",
f: "main.js",
t: "module",
}
npm install getopts
A short option consists of a -
followed by a single alphabetic character. Multiple options can be grouped together without spaces. Short options are boolean by default unless followed by an operand (non-option) or if adjacent to any non-alphabetic characters:
getopts(["-ab", "-c"]) //=> { _: [], a:true, b:true, c:true }
getopts(["-a", "alpha"]) //=> { _: [], a:"alpha" }
getopts(["-abc1"]) //=> { _: [], a:true, b:true, c:1 }
Use opts.string
to parse an option as a string regardless.
getopts(["-kF12"], {
string: ["k"],
}) //=> { _: [], k:"F12" }
The first operand following an option will be used as its value. Use opts.boolean
to specify that an option should be parsed as a boolean regardless, causing the following argument to be treated as an operand instead.
getopts(["-a", "alpha"], {
boolean: ["a"],
}) //=> { _: ["alpha"], a:true }
Any character listed in the ASCII table can be used as a short option if it's the first character after the dash.
getopts(["-9", "-#10", "-%0.01"]) //=> { _:[], 9:true, #:10, %:0.01 }
A long option consists of a --
followed by a name and a value separated by an =
. Long options without a value are boolean by default.
getopts(["--turbo", "--warp=10"]) //=> { _: [], turbo:true, warp:10 }
getopts(["--warp=e=mc^2"]) //=> { _: [], warp:"e=mc^2" }
getopts(["--@", "alpha"]) //=> { _: [], @:"alpha" }
Negated options start with --no-
and are always false
.
getopts(["--no-turbo"]) //=> { _: [], turbo:false }
Every non-option argument is an operand. Operands are saved to the result._
operands array.
getopts(["alpha", "-w9", "bravo"]) //=> { _: ["alpha", "bravo"], w:9 }
getopts(["--code=alpha", "bravo"]) //=> { _: ["bravo"], code:"alpha" }
Everything after a standalone --
is an operand.
getopts(["--alpha", "--", "--bravo", "--turbo"]) //=> { _:["--bravo", "--turbo"], alpha:true }
A single -
is also treated as an operand.
getopts(["--turbo", "-"]) //=> { _:["-"], turbo:true }
Options specified as boolean or string will be added to the result object as false
or ""
(even if missing from the arguments array).
getopts([], {
string: ["a"],
boolean: ["b"],
}) //=> { _:[], a:"", b:false }
Repeated options are stored as arrays with every value in order of appearance.
getopts(["-x?alpha=bravo", "-x3.14", "-x"] //=> { _:[], a:["?alpha=bravo", 3.14, true] }
A value may contain newlines or other control characters.
getopts(["--text=top\n\tbottom"]) //=> { _:[], text:"top\n\tbottom" }
="false"
is converted to boolean by default.
getopts(["--turbo=false"]) //=> { _:[], turbo:false }
getopts(argv, opts)
Parse command-line arguments. Returns an object mapping argument names to their values.
argv[]
An array of arguments, usually process.argv
.
opts.alias
An object of option aliases. An alias can be a string or an array of strings. Aliases let you declare substitute names for an option, e.g., the short (abbreviated) and long (canonical) variations.
getopts(["-t"], {
alias: {
turbo: ["t", "T"],
},
}) //=> { _:[], t:true, T:true, turbo:true }
opts.boolean
An array of options to parse as boolean. In the example below, t
is parsed as a boolean, causing the following argument to be treated as an operand.
getopts(["-t", "alpha"], {
boolean: ["t"],
}) //=> { _:["alpha"], t:true }
opts.string
An array of flags to parse as strings. In the example below, t
is parsed as a string, causing all adjacent characters to be treated as a single value and not as individual options.
getopts(["-atabc"], {
string: ["t"],
}) //=> { _:[], a:true, t:"abc" }
opts.default
An object of default values for options not present in the arguments array.
getopts(["--warp=10"], {
default: {
warp: 15,
turbo: true,
},
}) //=> { _:[], warp:10, turbo:true }
opts.unknown()
We call this function for each unknown option. Return false
to discard the option. Unknown options are those that appear in the arguments array, but are not in opts.string
, opts.boolean
, opts.default
, or opts.alias
.
getopts(["-abc"], {
unknown: (option) => "a" === option,
}) //=> { _:[], a:true }
opts.stopEarly
A boolean property. If true
, the operands array _
will be populated with all the arguments after the first operand.
getopts(["-w9", "alpha", "--turbo", "bravo"], {
stopEarly: true,
}) //=> { _:["alpha", "--turbo", "bravo"], w:9 }
This property is useful when implementing sub-commands in a CLI.
import getopts from "getopts"
import { install, update, uninstall } from "./commands.js"
const options = getopts(process.argv.slice(2), {
stopEarly: true,
})
const [command, subargv] = options._
if (command === "install") {
install(subargv)
} else if (command === "update") {
update(subargv)
} else if (command === "uninstall") {
uninstall(subargv)
}
npm --prefix bench start
FAQs
Parse CLI arguments.
The npm package getopts receives a total of 1,398,016 weekly downloads. As such, getopts popularity was classified as popular.
We found that getopts demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.